package gatecontrol.activities;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.util.ArrayList;
import java.util.List;

import adcp.network.beans.GateDownLoad;
import adcp.views.adapter.GateAdapter;
import gatecontrol.network.http.GetRealWaterGateDam;
import managers.DatabaseManager;
import managers.UIHandler;
import managers.UserInfo;
import shuiyuqing.network.http.DownloadInfo;

/**
 * Created by nimi on 2015/10/29.
 */
public class GateActivityControl extends UIHandler.BaseActivity implements GetRealWaterGateDam.Delegate {
    private Button back_gate;
    private Spinner gate_spinner;
    //private TextView gate_state;//水闸状态（在用良好|故障|已报废）
    private LinearLayout gate_running;//若水闸的状态为在用良好则显示该信息
    private TextView up_water;//闸上水位
    private TextView down_water;//闸下水位
    private TextView liuliang;//流量
    private RelativeLayout ggate2;
    private RelativeLayout ggate3;
    private RelativeLayout ggate4;
    private RelativeLayout ggate5;
    private TextView edit_gate1;
    private TextView edit_gate2;
    private TextView edit_gate3;
    private TextView edit_gate4;
    private TextView edit_gate5;
    private Button gate_con;
    // 没有数据
    TextView noneInfo;
    //private Button gate_level;//点击Button打开实时的闸门启度信息
    // 此处使用等同于一IrrWaterGate类就是为了区分闸门
    private List<GateDownLoad> gateDownLoads;
    private GateDownLoad gateDownLoad = new GateDownLoad();
    private GateDownLoad gateChoose = new GateDownLoad();
    private GateAdapter gateAdapter;
    //    private SQLiteHelper dbHelper;
    UserInfo userInfo;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_gate_control);
//        dbHelper=new SQLiteHelper(this, "im.db", null, 12);
        init();
        up_water = (TextView) findViewById(R.id.edit_up_water);
        down_water = (TextView) findViewById(R.id.edit_down_water);
        liuliang = (TextView) findViewById(R.id.edit_flowrate);
        edit_gate1 = (TextView) findViewById(R.id.edit_gate1);
        ggate2 = (RelativeLayout) findViewById(R.id.ggate2);
        edit_gate2 = (TextView) findViewById(R.id.edit_gate2);
        ggate3 = (RelativeLayout) findViewById(R.id.ggate3);
        edit_gate3 = (TextView) findViewById(R.id.edit_gate3);
        ggate4 = (RelativeLayout) findViewById(R.id.ggate4);
        edit_gate4 = (TextView) findViewById(R.id.edit_gate4);
        ggate5 = (RelativeLayout) findViewById(R.id.ggate5);
        edit_gate5 = (TextView) findViewById(R.id.edit_gate5);
        gate_running = (LinearLayout) findViewById(R.id.gate_running);
        gate_con = (Button) findViewById(R.id.gate_con);
        gate_con.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(GateActivityControl.this, GateSendActivity.class);
                Bundle bundle = new Bundle();//同时传递闸门数
                if (gateChoose != null) {
                    bundle.putFloat("num", gateChoose.getGate_hole());
                    bundle.putString("name", gateChoose.getGate_name());
                    bundle.putString("Scode", gateChoose.getStadia_code());//测站编码
                    bundle.putString("gateCode", gateChoose.getGate_num());//水闸编码
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    String sInfo = "请选择一个水闸！";
                    Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
                }
            }
        });

        noneInfo = (TextView) findViewById(R.id.noneInfo);
        noneInfo.setTypeface(MyApplication.iconfont);

        gate_spinner = (Spinner) findViewById(R.id.gate_choose);
        gate_spinner.setAdapter(gateAdapter);
        gate_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View arg1, int position,
                                       long arg3) {
                clear();
                gateChoose = gateAdapter.getItem(position);//得到用户选择的水闸信息：水闸名称、水闸编号、水闸孔数、测站编码
//                if (gateChoose.getGate_state() == 1) {
//                    System.out.print("是1");
//                    GetRealWaterGateDam dam = new GetRealWaterGateDam(gateChoose.getStadia_code());
//                    dam.setDelegate(GateActivityControl.this);
//                    dam.get();
//
//                } else {
//                    String sInfo = "该水闸不能正常使用";
//                    Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
//                }
                GetRealWaterGateDam dam = new GetRealWaterGateDam(gateChoose.getStadia_code());
                dam.setDelegate(GateActivityControl.this);
                dam.get();

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                String sInfo = "什么也没选！";
                Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
            }
        });


    }

    private void init() {
        gateDownLoads = new ArrayList<GateDownLoad>();

        SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
        db.beginTransaction();

        try {

            Cursor cursor = db.rawQuery("select t.* FROM t_IrrBAWaterGate as t order by t.orderNum asc",new String[]{});
            while (cursor.moveToNext()) {
                GateDownLoad gate = new GateDownLoad();
                gate.setGate_num(cursor.getString(cursor.getColumnIndex("watergateCode")));//水闸编号
                gate.setGate_name(cursor.getString(cursor.getColumnIndex("watergateName")));//水闸名称
                gate.setGate_hole(cursor.getFloat(cursor.getColumnIndex("watergateNUM")));//水闸孔数
                gate.setStadia_code(cursor.getString(cursor.getColumnIndex("stadiaCode")));//测站编码
                String gatestatus = (cursor.getString(cursor.getColumnIndex("watergateStatus")));
                gate.setGate_state(gatestatus.charAt(0));//水闸状态

                if (gate.getGate_num().startsWith("00000"))
                {
                    continue;
                }
                gateDownLoads.add(gate);

            }
            cursor.close();
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
            DatabaseManager.getInstance().closeDatabase();
        }
        gateAdapter = new GateAdapter(this, gateDownLoads);
        System.out.print(gateAdapter.getCount());

    }

    @Override
    public void onResponse(String response, GetRealWaterGateDam dam) {

        if (dam.getDownload().getStatus() == DownloadInfo.SUCCESS) {
            noneInfo.setVisibility(View.GONE);
            if (dam.getDownload().getRealTimeIrrBRWaterDam() != null && dam.getDownload() != null) {
                if (dam.getDownload().getRealTimeIrrBRWaterDam().getHeightDown() != null)
                    gateChoose.setDown_water(dam.getDownload().getRealTimeIrrBRWaterDam().getHeightDown().floatValue());
                else
                    gateChoose.setDown_water(0);
                if (dam.getDownload().getRealTimeIrrBRWaterDam().getHeightUp() != null)
                    gateChoose.setUp_water(dam.getDownload().getRealTimeIrrBRWaterDam().getHeightUp().floatValue());
                else
                    gateChoose.setUp_water(0);
                if (dam.getDownload().getRealTimeIrrBRWaterDam().getFluxGate() != null)
                    gateChoose.setFlow_rate(dam.getDownload().getRealTimeIrrBRWaterDam().getFluxGate().floatValue());
                else
                    gateChoose.setFlow_rate(0);
                if (dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree1() != null)
                    gateChoose.setOpen_level1(dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree1().floatValue());
                else
                    gateChoose.setOpen_level1(0);
                float f;
                edit_gate1.setText((f = gateChoose.getOpen_level1())<0?"!":f + "米");
                switch ((int) gateChoose.getGate_hole()) {
                    case 5:
                        if (dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree5() != null)
                            gateChoose.setOpen_level5(dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree5().floatValue());
                        else
                            gateChoose.setOpen_level5(0);
                        ggate5.setVisibility(View.VISIBLE);
                        edit_gate5.setText((f =gateChoose.getOpen_level5())<0?"!":f + "米");
                    case 4:
                        if (dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree4() != null)
                            gateChoose.setOpen_level4(dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree4().floatValue());
                        else
                            gateChoose.setOpen_level4(0);
                        ggate4.setVisibility(View.VISIBLE);
                        edit_gate4.setText((f =gateChoose.getOpen_level4())<0?"!":f + "米");
                    case 3:
                        if (dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree3() != null)
                            gateChoose.setOpen_level3(dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree3().floatValue());
                        else
                            gateChoose.setOpen_level3(0);
                        ggate3.setVisibility(View.VISIBLE);
                        edit_gate3.setText((f =gateChoose.getOpen_level3())<0?"!":f + "米");
                    case 2:
                        if (dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree2() != null)
                            gateChoose.setOpen_level2(dam.getDownload().getRealTimeIrrBRWaterDam().getOpenDegree2().floatValue());
                        else
                            gateChoose.setOpen_level2(0);
                        ggate2.setVisibility(View.VISIBLE);
                        edit_gate2.setText((f =gateChoose.getOpen_level2())<0?"!":f + "米");
                        break;
                    default:
                        break;
                }
                up_water.setText(gateChoose.getUp_water() + "米");
                down_water.setText(gateChoose.getDown_water() + "米");
                liuliang.setText(gateChoose.getFlow_rate() + "立方米/秒 ");
            }
            else
            {
                noneInfo.setVisibility(View.VISIBLE);
            }

        } else if (dam.getDownload().getStatus() == DownloadInfo.FAILED) {
            noneInfo.setVisibility(View.VISIBLE);
            String sInfo = "网络问题，请稍后再试！";
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }


    }

    private void clear() {
        up_water.setText("");
        down_water.setText("");
        liuliang.setText("");
        edit_gate1.setText("");
        ggate2.setVisibility(View.INVISIBLE);
        ggate3.setVisibility(View.INVISIBLE);
        ggate4.setVisibility(View.INVISIBLE);
        ggate5.setVisibility(View.INVISIBLE);

    }

    @Override
    public void onErrorResponse(VolleyError error, GetRealWaterGateDam dam) {
        String sInfo = "网络问题，请稍后再试！";
        Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_SHORT).show();
        noneInfo.setVisibility(View.VISIBLE);

    }
}
